<template>
  <el-card class="form-container" shadow="never">
    <el-form
      :model="homeAdvertise"
      :rules="rules"
      ref="form"
      label-width="150px"
      size="small"
    >
      <el-form-item label="广告位名称：" prop="name">
        <el-input v-model="homeAdvertise.name" class="input-width"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSave()">提交</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { axios } from "../../utils";

export default {
  name: "HomeAdvertiseDetail",
  //组件传参
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      homeAdvertise: { name: null },
      rules: {
        name: [
          { required: true, message: "请输入广告名称", trigger: "blur" },
          {
            min: 2,
            max: 140,
            message: "长度在 2 到 140 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },

  //钩子函数
  created() {
    // 如果isEdit==false时，为新增操作
    if (this.isEdit == false) {
      this.handleSave();
    }
    // 如果isEdit==true时，为编辑操作
    else {
      this.homeAdvertise.id = this.$route.params.id;
      // 根据id回显广告位
      this.loadPromotionSpace(this.homeAdvertise.id);
      this.handleSave();
    }
  },

  methods: {
    //方法1: 保存广告位信息
    handleSave() {
      const url = "/PromotionSpace/saveOrUpdatePromotionSpace";
      const data = {
        name: this.homeAdvertise.name,
        id: this.homeAdvertise.id,
      };
      axois.post(url, data)
        .then((resp) => {
          if (resp.data.state == 200) {
            this.$message.success(resp.data.message);
            this.$router.back();
          } else {
            this.$message.error(resp.data.message);
          }
        })
        .catch((error) => {
          this.$message.error("内部服务器错误，添加失败");
        });
    },

    //方法2: 回显广告位信息
    loadPromotionSpace(id) {
      // 根据id回显广告位信息
      this.axois
        .get("PromotionSpace/findPromotionSpaceById/" + id)
        .then((resp) => {
          Object.assign(resp.data.content, homeAdvertise);
        })
        .catch((error) => {
          this.$message.error("加载数据失败");
        });
    },
  },
};
</script>
<style scoped>
.input-width {
  width: 70%;
}
</style>
